/*
 *  Copyright (c) 2009, Baturu.COM. All rights reserved.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package com.baturu.oss.facade;

import com.baturu.oss.dao.OpenDAOManager;
import org.sitevelocity.exceptions.ServerInternalException;
import com.baturu.oss.entities.users.OpenUser;

/**
 * Manages users.
 * 
 * @author javafuns
 */
public class OpenUserFacade {

    /**
     * compute users count.
     * 
     * @return
     */
    public int getUserCount() {
        OpenDAOManager odm = OpenDAOManager.newInstance();
        odm.startTransaction();
        try {
            int c = odm.getUserDAO().getUserCount();
            odm.commitTransaction();
            return c;
        } finally {
            odm.close();
        }
    }

    /**
     * get user by its id.
     * @param id
     * @return
     * @throws ServerInternalException
     */
    public OpenUser getUser(String id) throws ServerInternalException {
        OpenDAOManager odm = OpenDAOManager.newInstance();
        OpenUser user = null;
        odm.startTransaction();
        try {
            user = odm.getUserDAO().getUser(id);
            odm.commitTransaction();
            return user;
        } catch (Exception e) {
            odm.rollback();
            throw new ServerInternalException(e);
        } finally {
            odm.close();
        }
    }

    /**
     * get user by its login name.
     * @param userId
     * @return
     * @throws ServerInternalException
     */
    public OpenUser getUserByLogin(String userId) throws ServerInternalException {
        OpenDAOManager odm = OpenDAOManager.newInstance();
        odm.startTransaction();
        try {
            OpenUser user = odm.getUserDAO().getUserByLogin(userId);
            odm.commitTransaction();
            return user;
        } catch (Exception e) {
            odm.rollback();
            throw new ServerInternalException(e);
        } finally {
            odm.close();
        }
    }

    public OpenUser saveUser(OpenUser ou) throws ServerInternalException {
        OpenDAOManager odm = OpenDAOManager.newInstance();
        odm.startTransaction();
        try {
            OpenUser user = odm.getUserDAO().newUser(ou);
            odm.commitTransaction();
            return user;
        } catch (Exception e) {
            odm.rollback();
            throw new ServerInternalException(e);
        } finally {
            odm.close();
        }
    }
}
